package me.wangcai.trafficpoliceai.controller;

import lombok.SneakyThrows;
import me.wangcai.trafficpoliceai.model.ResponseInfo;
import me.wangcai.trafficpoliceai.service.IVideoService;
import me.wangcai.trafficpoliceai.service.impl.VideoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;

@RestController
@RequestMapping("/video")
public class VideoController {

    private final String PATH = "E:/wangcai/a/video/";

    @Autowired
    private IVideoService videoServiceImpl;

    @SneakyThrows
    @GetMapping("/play/{video}")
    public ResponseInfo getVideo(@PathVariable Integer video){
        return videoServiceImpl.playVideo(video);
    }


    @PostMapping("/list")
    public ResponseInfo getVideoList(){
        return ResponseInfo.success("获取成功",videoServiceImpl.getVideoList());
    }

    @SneakyThrows
    @PostMapping("/upload")
    public ResponseInfo handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        for (MultipartFile file : files) {
            if(!file.getContentType().equalsIgnoreCase("video/mp4") && !file.getContentType().equalsIgnoreCase("audio/mpeg")){
                return ResponseInfo.error("上传内容含不是视频的文件");
            }
        }
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            //文件绝对路径,项目中一般使用相对类路径,即使文件变更路径也会跟着
            if (!file.isEmpty()) {
                byte[] bytes = file.getBytes();
                stream = new BufferedOutputStream(new FileOutputStream(
                        PATH + file.getOriginalFilename()));//设置文件路径及名字
                stream.write(bytes);// 写入
                stream.close();
            }
        }
        return ResponseInfo.success("上传成功!");
    }
}
